package com.combetter.changxing.bindingconfig;

import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.combetter.changxing.R;
import com.combetter.changxing.ui.view.Banner.Banner;

/**
 * Created by Mark.fan on 2018/5/14.
 */

public class RecyclerViewItemClickSupport {
    private final RecyclerView mRecyclerView;

    private OnItemClickListener mOnItemClickListener;
        //
    private Banner.OnBannerClickListener mOnBannerClickListener;

    /**
     * 通用item点击
     */
    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mOnItemClickListener != null) {
                RecyclerView.ViewHolder holder =  mRecyclerView.getChildViewHolder(v);
                mOnItemClickListener.onItemClick(mRecyclerView, holder.getAdapterPosition(), v);
            }
        }
    };

    public RecyclerViewItemClickSupport(RecyclerView recyclerView){
        mRecyclerView = recyclerView;
        mRecyclerView.setTag(R.id.item_click_support, this);
        mRecyclerView.addOnChildAttachStateChangeListener(mAttachListener);
    }


    private RecyclerView.OnChildAttachStateChangeListener mAttachListener = new RecyclerView.OnChildAttachStateChangeListener() {
        @Override
        public void onChildViewAttachedToWindow(View view) {
            if (view instanceof Banner && mOnBannerClickListener != null) {
                Banner banner = (Banner) view;
                banner.setOnBannerClickListener(mOnBannerClickListener);
                return;
            }
            if (mOnClickListener != null) {
                view.setOnClickListener(mOnClickListener);
            }
        }

        @Override
        public void onChildViewDetachedFromWindow(View view) {

        }
    };

    public static RecyclerViewItemClickSupport addTo(RecyclerView recyclerView) {
        RecyclerViewItemClickSupport support = (RecyclerViewItemClickSupport) recyclerView.getTag(R.id.item_click_support);
        if (support == null) {
            support = new RecyclerViewItemClickSupport(recyclerView);
        }
        return support;
    }

    public RecyclerViewItemClickSupport setOnItemClickListener(OnItemClickListener listener) {
        mOnItemClickListener = listener;
        return this;
    }

    public RecyclerViewItemClickSupport setOnBannerClickListener(Banner.OnBannerClickListener listener) {
        mOnBannerClickListener = listener;
        return this;
    }

    public interface OnItemClickListener{
        void onItemClick(RecyclerView recyclerView, int position, View view);
    }
}
